﻿using DotNetSpeech;
using System;
using System.Windows.Forms;

namespace function
{
    public partial class UserControlread : UserControl
    {
        public UserControlread()
        {
            InitializeComponent();

            sp = new SpVoice();
        }

        public UserControlread(string content)
        {
            InitializeComponent();
            this.richTextBox1.Text = content;
            //txtContent = content;
            Read(content);

            sp = new SpVoice();
        }

        public void Stop()
        {
            try
            {
                sp.Pause();
                sp.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
            }
            catch (Exception ex)
            {
                //ImcpLog.WrtieExceptionLog("AlarmBroadcaster", "Stop", ex.Message, ex.StackTrace);
            }
        }

        private string txtContent;

        private void btnRead_Click(object sender, EventArgs e)
        {
            txtContent = this.richTextBox1.Text;

            if (string.IsNullOrEmpty(txtContent))
                Read("请输入需要朗读的文本");
            else
                Read(txtContent);
        }

        private SpVoice sp;

        private void Read(string text)
        {
            if (sp == null)
                sp = new SpVoice();

            //var a = sp.GetVoices();

            //sp.Voice = a.Item(0);

            sp.Rate = GetSpeedSelected();

            //sp.Voice=

            SpeechVoiceSpeakFlags sFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;

            //sp.DisplayUI();
            sp.Speak(text, sFlags);
        }

        private int GetSpeedSelected()
        {
            //if (rbtnFast.Checked) { return 2; }
            //if (rbtnNomal.Checked) { return 0; }
            //if (rbtnSlow.Checked) { return -3; }
            return 0;
        }

        private bool flag;

        private void button1_Click(object sender, EventArgs e)
        {
            if (flag)
            {
                flag = false;
                sp.Resume();
                this.button1.Text = "停止";
                return;
            }

            if (sp != null)
            {
                flag = true;
                sp.Pause();
                this.button1.Text = "继续";
            }
        }

        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            sp.Rate = this.trackBar1.Value;
            //sp.Pause();
            //sp.Resume();
        }

        private void UserControlread_Load(object sender, EventArgs e)
        {
            var a = sp.GetVoices();
            string s = "";
            foreach (ISpeechObjectToken item in a)
            {
                s += item.GetDescription() + "\n";
            }

            this.label1.Text = s;
        }
    }
}